using System;
using System.Collections.Generic;
using System.Linq;
using Habanero.Base;
using Habanero.Base.Exceptions;
using Habanero.BO;

namespace FireStarterModeller.BO
{
    public class DMClassDuplicateUIViewNameRule : IBusinessObjectRule
    {
        private string _classToString;
        private string _viewName;

/*        public DMClassDuplicateUIViewNameRule()
        {
//            if (dmClass == null) throw new ArgumentNullException("dmClass");
//            _dmClass = dmClass;
        }*/

        public bool IsValid()
        {
//            return this.IsValid(_dmClass);
            throw new HabaneroApplicationException("The IsValid is no longer Valid you should use the IsValid(bo) method");
        }

        public bool IsValid(IBusinessObject bo)
        {
            DMClass dmClass = (DMClass)bo;
            _classToString = dmClass.ToString();
            BusinessObjectCollection<UIView> uiViews = dmClass.UIViews;
            if (uiViews.Count < 2) return true;
            var viewCounts = uiViews
                    .Where(uiView => !String.IsNullOrEmpty(uiView.ViewName))
                    .GroupBy(view => new {view.ViewName } )
                    .Select(group => new {ViewName = group.Key, Count = group.Count() });

            var allDuplicateViews = viewCounts.Where(viewCount => viewCount.Count > 1);
            var hasDuplicateViews = allDuplicateViews.Count() > 0;
            if (hasDuplicateViews) _viewName = allDuplicateViews.First().ViewName.ToString();
            return !hasDuplicateViews;
        }

        public string Name
        {
            get { return "DMClassDuplicateUIViewName"; }
        }

        public string Message
        {
            get
            {
                return "The Entity/Class '" + _classToString +
                       "' cannot have more than one UIView with the same name('" + _viewName + "').";
            }
        }

        public ErrorLevel ErrorLevel
        {
            get { return Habanero.Base.ErrorLevel.Warning; }
        }
    }
}